package com.opesoft.calendar.biz;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import com.opesoft.calendar.model.Note;
import com.opesoft.pf.jpa.SessionManager;

public class NoteBO
{
	Logger log=Logger.getLogger(this.getClass());

	public void save(Note note)
	{
		EntityManager em=SessionManager.open();
		em.persist(note);
		SessionManager.commit();
	}

	@SuppressWarnings("unchecked")
	public String[][] searchInDay(int year,int month,int day)
	{
		String date=DateUtils.intDate2Str(year,month,day);

		EntityManager em=SessionManager.open();
		List<Note> list=em.createQuery("select x from Note x where x.date = '"+date+"'").getResultList();
		if(list!=null)
		{
			String[][] result=new String[list.size()][];
			int index=0;
			for(Note note : list)
			{
				String[] line=new String[7];
				line[0]=note.getId()+"";
				line[1]=note.getDate()+"";
				line[2]=note.getStartTime();
				line[4]=note.getEndTime();
				line[5]=note.getName();
				line[6]=note.getIco();

				result[index++]=line;
			}
			return result;
		}

		return new String[0][];
	}

	@SuppressWarnings("unchecked")
	public String[][] searchInDay(int year,int month,int day,Long[] types)
	{
		String date=DateUtils.intDate2Str(year,month,day);
		StringBuffer inCondition=new StringBuffer();
		if(types!=null)
		{
			for(long type : types)
			{
				if(inCondition.length()>1) inCondition.append(","+type);
				else inCondition.append(type);
			}
		}

		if(inCondition.length()<1) inCondition.append("0");

		EntityManager em=SessionManager.open();
		List<Note> list=em.createQuery("select x from Note x where x.date = '"+date+"' and x.noteTypeId in ("+inCondition.toString()+")").getResultList();
		if(list!=null)
		{
			String[][] result=new String[list.size()][];
			int index=0;
			for(Note note : list)
			{
				String[] line=new String[7];
				line[0]=note.getId()+"";
				line[1]=note.getDate()+"";
				line[2]=note.getStartTime();
				line[4]=note.getEndTime();
				line[5]=note.getName();
				log.debug("*****>"+note.getName());
				line[6]=note.getIco();

				result[index++]=line;
			}
			return result;
		}

		return new String[0][];
	}

	public List<Object> search(long id)
	{
		EntityManager em=SessionManager.open();
		Note note=em.find(Note.class,id);
		if(note!=null)
		{
			List<Object> list=new ArrayList<Object>();
			list.add(note.getId());
			list.add(note.getName());
			list.add(note.getRemark());
			return list;
		}
		return new ArrayList<Object>();
	}
}
